import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MaxNLocator
from scipy.signal import savgol_filter

plt.rcParams["font.family"] = ["SimSun", "Times New Roman"]
plt.rcParams['axes.unicode_minus'] = False  # 正确显示负号

# 绘图配置参数
config = {
    'file_path': 'T3里程分析.xlsx',  # Excel文件路径
    'output_path': '面积图分析.png',  # 输出图片路径
    'figure_width': 10,  # 图表宽度（英寸）
    'figure_height': 7,  # 图表高度（英寸）
    'dpi': 300,  # 图片分辨率
    'xlim_max': 100,  # X轴最大刻度
    'smooth_window': 9,  # 平滑窗口大小
    'smooth_polyorder': 3,  # 平滑多项式阶数
    'sample_points': 10,  # 采样点数量
    'colors': {
        'delta_L': '#FF6B6B',  # 柔和的红色
        'theta': '#4ECDC4',    # 柔和的青色
        'grid': '#E0E0E0',     # 浅灰色网格
        'text': '#292F36',     # 深色文本
        'background': '#F7F7F7' # 浅灰色背景
    }
}

def plot_cumulative_mileage(config):
    df = pd.read_excel(config['file_path'])
    theta_cumulative = df['Δθ累积量']
    delta_L_cumulative = df['ΔL累积量']
    cumulative_mileage = df['累积里程']
    plt.figure(figsize=(config['figure_width'], config['figure_height']), 
                facecolor=config['colors']['background'])
    ax = plt.gca()
    ax.set_facecolor(config['colors']['background'])
    x = range(len(cumulative_mileage))
    plt.fill_between(x, delta_L_cumulative, label=r'$\Delta L$累积量', 
                        alpha=0.7, color=config['colors']['delta_L'])
    plt.fill_between(x, delta_L_cumulative, delta_L_cumulative + theta_cumulative, 
                        label=r'$\Delta \theta$累积量', alpha=0.7, 
                        color=config['colors']['theta'])
    plt.title('累积里程面积分析图', fontsize=18, pad=20, color=config['colors']['text'])
    plt.xlabel('栅格序号', fontsize=14, labelpad=10, color=config['colors']['text'])
    plt.ylabel('累积里程', fontsize=14, labelpad=10, color=config['colors']['text'])
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_color(config['colors']['text'])
    ax.spines['bottom'].set_color(config['colors']['text'])
    ax.tick_params(axis='both', which='major', labelsize=12, 
                    colors=config['colors']['text'])
    plt.grid(True, linestyle='--', alpha=0.5, color=config['colors']['grid'])
    plt.xlim(0, config['xlim_max'])
    ax.xaxis.set_major_locator(MaxNLocator(integer=True))
    legend = plt.legend(fontsize=12, frameon=True, loc='upper left')
    frame = legend.get_frame()
    frame.set_facecolor(config['colors']['background'])
    frame.set_edgecolor(config['colors']['grid'])
    frame.set_alpha(0.8)
    sample_indices = np.linspace(0, len(cumulative_mileage)-1, 
                                config['sample_points'], dtype=int)
    plt.scatter([x[i] for i in sample_indices], 
                [delta_L_cumulative[i] for i in sample_indices], 
                color=config['colors']['delta_L'], s=30, alpha=0.8)
    plt.scatter([x[i] for i in sample_indices], 
                [delta_L_cumulative[i] + theta_cumulative[i] for i in sample_indices], 
                color=config['colors']['theta'], s=30, alpha=0.8)
    smooth_delta_L = savgol_filter(delta_L_cumulative, 
                                    window_length=config['smooth_window'], 
                                    polyorder=config['smooth_polyorder'])
    smooth_theta = savgol_filter(delta_L_cumulative + theta_cumulative, 
                                window_length=config['smooth_window'], 
                                polyorder=config['smooth_polyorder'])
    plt.plot(x, smooth_delta_L, color='#E63946', alpha=0.8, linewidth=1.5)
    plt.plot(x, smooth_theta, color='#1D3557', alpha=0.8, linewidth=1.5)
    plt.tight_layout()
    plt.savefig(config['output_path'], dpi=config['dpi'], 
                facecolor=config['colors']['background'])
    plt.show()

plot_cumulative_mileage(config)